package com.tbit.uqbike.client.business.machine_op_log.service;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tbit.common.constant.OperationPlatform;
import com.tbit.common.entity.MachineOpLog;
import com.tbit.common.entity.UserOpLog;
import com.tbit.common.utils.TraceUtil;
import com.tbit.uqbike.client.dao.log.MachineOpLogDao;
import com.tbit.uqbike.client.business.user_op_log.service.UserOpLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author <a href="mailto:zheng.zebiao@tbit.com.cn">zb</a>
 * @since 2024/11/22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MachineOpLogService {
    final MachineOpLogDao machineOpLogDao;
    final UserOpLogService userOpLogService;

    public void insertSingle(MachineOpLog machineOpLog) {
        try {
            StringBuilder detail = new StringBuilder(ObjUtil.defaultIfNull(machineOpLog.getDetail(), ""));
            String traceId = TraceUtil.getTraceIdByLocal();
            if (traceId != null) {
                if (detail.length() > 0) {
                    detail.append("\n");
                }
                detail.append("TraceID: ")
                        .append(traceId);
            }
            if (machineOpLog.getOpUserPhone() != null && machineOpLog.getOpUser() == null) {
                machineOpLog.setOpUser("未实名");
            }
            machineOpLog.setDetail(detail.length() > 0 ? detail.toString() : null);
            machineOpLogDao.insert(machineOpLog);

            // 顺便插入用户操作日志
            UserOpLog userOpLog = UserOpLog.builder()
                    .accountId(machineOpLog.getAccountId())
                    .operation(machineOpLog.getOperation())
                    .opType(machineOpLog.getOpType())
                    .opUser(machineOpLog.getOpUser())
                    .opUserPhone(machineOpLog.getOpUserPhone())
                    .opPlatform(OperationPlatform.CLIENT.code)
                    .opTime(LocalDateTime.now())
                    .result(machineOpLog.getResult())
                    .detail(detail + (detail.length() > 0 ? "\n" : "") + "车辆编号: " + machineOpLog.getUserCode() + "\n中控编号: " + machineOpLog.getMachineNO())
                    .build();
            userOpLogService.save(userOpLog);
        } catch (Exception e) {
            log.error("[车辆操作日志] 插入失败: {}", machineOpLog, e);
        }
    }
}
